package com.me.bbs.aop;

import com.me.bbs.anno.RequireAdmin;
import com.me.bbs.common.AdminType;
import com.me.bbs.common.CommonConst;
import com.me.bbs.common.SessionUtils;
import com.me.bbs.exceptions.NoAuthException;
import com.me.bbs.exceptions.NoLoginException;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author Liming Wang
 * @Description
 * @Create 2023/1/29 21:45
 */
@Aspect
@Component
public class Authority {
    @Pointcut("execution(* com.me.bbs.controller..*(..))")
    private void controllerMethodWithAuthAnno(){}

//    @Before(value = "controllerMethodWithAuthAnno() && @annotation(requireAdmin)"
//            ,argNames = "requireAdmin"
//        )
    public void checkAdmin(RequireAdmin requireAdmin){
        if(requireAdmin.value() == null || !StringUtils.hasLength(requireAdmin.forum()))
            throw new IllegalArgumentException("RequireAdmin参数不能为空");
        if(SessionUtils.getAttribute("user") == null)
            throw new NoLoginException();
        Long forumId = Long.parseLong(requireAdmin.forum());
        List<Long> adminedForums = (List<Long>) SessionUtils.getAttribute(CommonConst.ADMIN_FORUMS);
        List<Long> ownedForums = (List<Long>) SessionUtils.getAttribute(CommonConst.OWNED_FORUMS);
        if(requireAdmin.value() == AdminType.ADMIN && (!adminedForums.contains(forumId) || !ownedForums.contains(forumId)))
            throw new NoAuthException();
        if(requireAdmin.value() == AdminType.OWNER && !ownedForums.contains(forumId))
            throw new NoAuthException();
    }
    @Before(value = "controllerMethodWithAuthAnno() && @annotation(com.me.bbs.anno.RequireLogin)"

    )
    public void checkLogin(){
        if(SessionUtils.getAttribute("user") == null)
            throw new NoLoginException();
    }
}
